from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *
from math import *
import Ui_billingUtilityEdit
import master.utility as utility

class BillingUtilEdit(QDialog, Ui_billingUtilityEdit.Ui_billingUtilityEditDlg):
  StyleSheet = """
QLineEdit[mandatory="true"] {
    background-color: rgb(255, 255, 127);
    color: darkblue;
}
"""
  def __init__(self, dbConn, tipe, dataGlob, parent=None):
        super(BillingUtilEdit, self).__init__(parent)
        self.setupUi(self)
        self.db = dbConn
        self.tipe = tipe
        self.dataGlob = dataGlob
        self.util = utility.Utility(self.db)
        
        self.mastModel = QSqlTableModel(self)
        self.mastModel.setTable("trans_billing")
        self.mastModel.setEditStrategy(QSqlTableModel.OnManualSubmit)
        
        self.detModel = QSqlRelationalTableModel(self)
        self.detModel.setTable("trans_billing_detail")
#        self.detModel.setRelation(0, QSqlRelation("v_master_kode_perkiraan", "kode_perkiraan", "nama"))
        self.detModel.setEditStrategy(QSqlTableModel.OnManualSubmit)
        self.detModel.setFilter("no_inv = '"+self.tipe+"'")
        self.detModel.setHeaderData(0, Qt.Horizontal, QVariant("No Bill"))
        self.detModel.setHeaderData(2, Qt.Horizontal, QVariant("Tarif Code"))
        self.detModel.setHeaderData(3, Qt.Horizontal, QVariant("Start"))
        self.detModel.setHeaderData(4, Qt.Horizontal, QVariant("End"))
        self.detModel.setHeaderData(5, Qt.Horizontal, QVariant("Qty"))
        self.detModel.setHeaderData(6, Qt.Horizontal, QVariant("Subtotal (Rp)"))
        self.detModel.setHeaderData(7, Qt.Horizontal, QVariant("Usage (Rp)"))
        self.detModel.setHeaderData(7, Qt.Horizontal, QVariant("Abonemen (Rp)"))
        self.detModel.setHeaderData(7, Qt.Horizontal, QVariant("CT"))
        self.detModel.setHeaderData(7, Qt.Horizontal, QVariant("Capacity(VA)"))
        self.detModel.setHeaderData(7, Qt.Horizontal, QVariant("PPJU(%)"))
        self.detModel.setHeaderData(7, Qt.Horizontal, QVariant("Admin(%)"))
        self.detModel.setHeaderData(7, Qt.Horizontal, QVariant("Hours/Day"))
        self.detModel.setHeaderData(7, Qt.Horizontal, QVariant("Max Admin (Rp)"))
        self.detModel.setHeaderData(7, Qt.Horizontal, QVariant("Meter No"))
        self.connect(self.detModel, SIGNAL("dataChanged(QModelIndex,QModelIndex)"), self.hitungTotal)
        self.detModel.select()
        
        self.detail_tbv.setModel(self.detModel)
        self.detail_tbv.setItemDelegate(DetailDelegate(self))
        self.detail_tbv.setSelectionMode(QTableView.SingleSelection)
        self.detail_tbv.setSelectionBehavior(QTableView.SelectRows)
        self.detail_tbv.setColumnHidden(1, True)
        self.detail_tbv.setColumnWidth(0, 100)
        
        self.tarifModel = QSqlTableModel(self)
        self.tarifModel.setTable("master_tarif_detail")
        self.tarifModel.setFilter("status = 'A' and kode_jenis_tarif not like 'S%'")
        self.tarifModel.select()
        
        self.initData()
        
#        self.lineedits = (self.desc_le, self.ref_le)
#        for lineEdit in self.lineedits:
#            lineEdit.setProperty("mandatory", QVariant(True))
#        self.setStyleSheet(BillingUtilEdit.StyleSheet)

  @pyqtSignature("")
  def on_save_pb_clicked(self):
      if self.invNo_le.text() == "":
          if self.tambahData():
              self.close()
          else:
              QMessageBox.warning(self, "Billing Utility","Can't add new data.")
      else:
          if self.updateData():
              self.close()
          else:
              QMessageBox.warning(self, "Billing Utility","Can't update data.")

  @pyqtSignature("")
  def on_cancel_pb_clicked(self):
      self.close()

  @pyqtSignature("")
  def on_add_pb_clicked(self):
      self.urut += 1
      if self.no_le.text() == "":
          if not self.tambahData():
              QMessageBox.warning(self, "Billing Utility","Can't add new data.")
              return
          self.detModel.setFilter("no_jurnal = '"+self.no_le.text()+"'")
          self.detModel.select()
      QSqlDatabase.database().transaction()
      row = self.detModel.rowCount()      
      self.detModel.insertRow(row)
      self.detModel.setData(self.detModel.index(row, 1), QVariant(self.no_le.text()))
      self.detModel.setData(self.detModel.index(row, 4), QVariant(self.urut))
#      self.detModel.submitAll()
      QSqlDatabase.database().commit()
      index = self.detModel.index(row, 0)
      self.detail_tbv.setCurrentIndex(index)
      self.detail_tbv.edit(index)

  @pyqtSignature("")
  def on_del_pb_clicked(self):
      index = self.detail_tbv.currentIndex()
      if not index.isValid():
          return
      self.detModel.removeRow(index.row())
      self.detModel.submitAll()
      
  def tambahData(self):
      if not self.validasi():          
          return
      idBaru = self.idBaru()
      self.no_le.setText(idBaru)
      hari = self.util.getServerToday()
      self.auditTime_dte.setDateTime(hari)
      tgl = hari.date().toString("yyyy-MM-dd")
      self.mastModel.setFilter("tgl_jurnal = '"+tgl+"'")
      self.mastModel.select()     
      QSqlDatabase.database().transaction()
      if not self.mastModel.insertRow(0):
          return
      self.mastModel.setData(self.mastModel.index(0, 0), QVariant(self.tgl_de.date()))
      self.mastModel.setData(self.mastModel.index(0, 1), QVariant(self.no_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 2), QVariant(self.desc_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 3), QVariant(self.auditUser_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 12), QVariant(hari))
      if not self.mastModel.submitAll():
          return
      if not QSqlDatabase.database().commit():
          return
      self.tipe = idBaru
      return True
      
  def updateData(self):
      self.detModel.submitAll()
#      self.hitungTotal()
      if not self.validasi():
          return
      self.mastModel.setFilter("no_jurnal = '"+self.tipe+"'")
      self.mastModel.select()
      QSqlDatabase.database().transaction()
      self.mastModel.setData(self.mastModel.index(0, 0), QVariant(self.tgl_de.date()))
      self.mastModel.setData(self.mastModel.index(0, 1), QVariant(self.no_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 2), QVariant(self.desc_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 4), QVariant(self.bank_de.date()))
      self.mastModel.setData(self.mastModel.index(0, 5), QVariant(self.due_de.date()))
      self.mastModel.setData(self.mastModel.index(0, 6), QVariant(self.ref_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 7), QVariant(self.unit_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 9), QVariant(self.refj_le.text()))
      self.per_le.setText(self.tgl_de.date().toString("yyyy-MM"))
      self.mastModel.setData(self.mastModel.index(0, 10), QVariant(self.per_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 11), QVariant(self.tipe_cmb.currentText()))
      if not self.mastModel.submitAll():
          return
      if not QSqlDatabase.database().commit():
          return
      return True
      
  def initData(self):
      hari = self.util.getServerToday()
      self.prep_le.setText(self.dataGlob["nama"])
      if self.tipe != "add":
          query = QSqlQuery(self.db)          
          qStr = "select m.no_inv ,m.kode_unit ,m.tgl_cetak ,m.periode_awal ,m.periode_akhir ,m.due_date ,m.listrik ,m.air ,m.gas ,m.denda ,m.materai ,m.hutang ,m.bayar ,m.cr_note ,m.tertagih_util ,m.pay_utilities ,m.posted ,m.status_pay ,m.level_jabatan ,m.level_billing ,m.user_name ,m.cetak_rpt ,m.bayar_listrik ,m.hutang_listrik ,m.bayar_air ,m.hutang_air ,m.bayar_gas ,m.hutang_gas ,m.bayar_materai ,m.hutang_materai ,m.pay_listrik ,m.pay_air ,m.pay_gas ,m.last_payment ,m.prev_balance ,m.nama_unit ,m.id_alamat from trans_billing m where m.no_inv = '"+self.tipe+"'"
          query.exec_(qStr)
          query.next()
          self.invNo_le.setText(unicode(query.value(0).toString()))
          self.per_le.setText(unicode(query.value(1).toString()))
          self.unit_le.setText(unicode(query.value(2).toString()))
          self.sqrm_le.setText(unicode(query.value(3).toString()))
          self.tarifSc_le.setText(unicode(query.value(4).toString()))
          self.tarifSf_le.setText(unicode(query.value(5).toString()))
          self.start_de.setDate(query.value(8).toDate())
          self.end_de.setDate(query.value(9).toDate())
          self.invDate_de.setDate(query.value(10).toDate())
          self.due_de.setDate(query.value(11).toDate())          
          self.paySc_le.setText(unicode(query.value(12).toString()))
          self.paySf_le.setText(unicode(query.value(13).toString()))
          self.outsSf_le.setText(unicode(query.value(14).toString()))
          self.outsSc_le.setText(unicode(query.value(15).toString()))
          self.met_le.setText(unicode(query.value(16).toString()))
          
          self.name_le.setText(unicode(query.value(2).toString()))
          self.billName_le.setText(unicode(query.value(3).toString()))
          self.billAddr_le.setText(unicode(query.value(4).toString()))
          self.billCity_le.setText(unicode(query.value(5).toString()))
          self.sc_le.setText(unicode(query.value(5).toString()))
          self.sf_le.setText(unicode(query.value(5).toString()))
          self.vat_le.setText(unicode(query.value(5).toString()))
          self.prev_le.setText(unicode(query.value(5).toString()))
          self.last_le.setText(unicode(query.value(5).toString()))
          self.payVat_le.setText(unicode(query.value(5).toString()))
          self.outsVat_le.setText(unicode(query.value(5).toString()))
          self.payMet_le.setText(unicode(query.value(5).toString()))
          self.outsMet_le.setText(unicode(query.value(5).toString()))          
          self.tax_de.setDate(query.value(6).toDate())          
          self.taxId_le.setText(unicode(query.value(7).toString()))
          self.statScPaid_cmb.setCurrentIndex(0)
          self.statSfPaid_cmb.setCurrentIndex(0)
          self.statScPost_cmb.setCurrentIndex(0)
          self.statSfPost_cmb.setCurrentIndex(0)
          self.statPaid_cmb.setCurrentIndex(0)
          self.statBill_cmb.setCurrentIndex(0)
          self.manager_le.setText(unicode(query.value(10).toString()))
          self.acc_le.setText(unicode(query.value(10).toString()))
          self.prep_le.setText(unicode(query.value(10).toString()))
          
  def idBaru(self):
      kode = "JV"
      per = self.util.getServerToday().date().toString("MMyyyy")
      noAkhir = self.util.getNewId(kode, per, "trans jurnal")
      id = kode+"-"+per+"-"+"0"*(6 - len(str(noAkhir)))+str(noAkhir)
      return id
            
  def hitungTotal(self):
      totBrs = self.detModel.rowCount()
      jum = 0
      for i in range(totBrs):
          record = self.detModel.record(i)
          jum += record.value(2).toDouble()[0]
      
  def validasi(self):
      valid = True
#      for lineEdit in self.lineedits:
#           if lineEdit.text().isEmpty():
#               QMessageBox.warning(self, "Journal","Data not valid / Empty column.")
#               return False
      return valid


class DetailDelegate(QSqlRelationalDelegate):
    def __init__(self, parent=None):
        super(DetailDelegate, self).__init__(parent)
        self.coaModel = QSqlQueryModel(self)
        self.coaModel.setQuery("select kode_perkiraan, nama from master_kode_perkiraan where detail = 'Y' order by kode_perkiraan")
        
    def paint(self, painter, option, index):
        myoption = QStyleOptionViewItem(option)
        if index.column() == 2 or index.column() == 3:
            myoption.displayAlignment |= Qt.AlignRight|Qt.AlignVCenter
        QSqlRelationalDelegate.paint(self, painter, myoption, index)
        
#    def createEditor(self, parent, option, index):
#        if index.column() == 0:
#            editor = QComboBox(parent)
#            editor.setModel(self.coaModel)
#            editor.setModelColumn(1)
#            editor.setCurrentIndex(0)                    
#            return editor
#        else:
#            return QSqlRelationalDelegate.createEditor(self, parent, option, index)
#            
#    def setEditorData(self, editor, index):
#        if index.column() == 0:
#            text = index.model().data(index, Qt.DisplayRole).toString()
#            brs = editor.match(index, 0, text, 1, Qt.MatchWrap )
#            editor.setCurrentIndex(brs[0].row())
#        else:
#            QSqlRelationalDelegate.setEditorData(self, editor, index)
#            
#    def setModelData(self, editor, model, index):
#        if index.column() == 0:
#            model.setData(index, QVariant(editor.currentIndex()))
#        else:
#            QSqlRelationalDelegate.setModelData(self, editor, model, index)
            
if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    form = BillingUtilEdit()
    form.show()
    app.exec_()
